//
//  SGPhotoList.m
//  朋友圈
//
//  Created by gzz on 2017/6/24.
//  Copyright © 2017年 gzz. All rights reserved.
//

#import "SGPhotoList.h"

#define CollectionName [[NSBundle mainBundle].infoDictionary valueForKey:(__bridge NSString *)kCFBundleNameKey]
#define kMaxImageWidth 500

static SGPhotoList *sharePhotoTools = nil;

@implementation SGPhotoAblumList

@end
@implementation SGPhotoList

+(instancetype)sharePhotoTools
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharePhotoTools = [[self alloc]init];
    });
    return sharePhotoTools;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharePhotoTools = [super allocWithZone:zone];
    });
    return sharePhotoTools;
}
//




- (void)saveImageToAblum:(UIImage *)image completion:(void (^)(BOOL, PHAsset *))completion
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusDenied) {
        if (completion) completion(NO, nil);
    } else if (status == PHAuthorizationStatusRestricted) {
        if (completion) completion(NO, nil);
    } else {
        __block NSString *assetId = nil;
        
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            assetId = [PHAssetCreationRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (!success) {
                if (completion) completion(NO, nil);
                return;
            }
            if(assetId == nil){
                if (completion) completion(NO,nil);
                return;
            }
            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil].lastObject;
            
            PHAssetCollection *desCollection = [self getDestinationCollection];
            if (!desCollection) completion(NO, nil);
            
            //save image
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                [[PHAssetCollectionChangeRequest changeRequestForAssetCollection:desCollection] addAssets:@[asset]];
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                if (completion) completion(success, asset);
            }];
        }];
    }

}

- (PHAssetCollection *)getDestinationCollection
{
    //To find whether have created a custom photo album
    PHFetchResult<PHAssetCollection *> *collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collection in collectionResult) {
        if ([collection.localizedTitle isEqualToString:CollectionName]) {
            return collection;
        }
    }
    //The new custom photo album
    __block NSString *collectionId = nil;
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        collectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:CollectionName].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    if (error) {
        NSLog(@"create album：%@failed", CollectionName);
        return nil;
    }
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionId] options:nil].lastObject;
}

-(NSArray <SGPhotoAblumList *>*)getPhotoAblumList
{
    NSMutableArray<SGPhotoAblumList *> *photoAblumList = [NSMutableArray array];
    __weak typeof(self)  weakSelf = self;
//    获取系统相册资源
    
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
   [smartAlbums enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL *stop)
    {
        if (collection.assetCollectionSubtype != 202 && collection.assetCollectionSubtype < 212) {
            __strong typeof (weakSelf) strongSelf = self;
            
            NSArray <PHAsset *> *asset = [strongSelf getAssetsInAssetCollection:collection ascending:NO];
            
            if (asset.count >0) {
                SGPhotoAblumList *ablum = [[SGPhotoAblumList alloc]init];
                ablum.tittle = [strongSelf transFormPhotoTitle:collection.localizedTitle];
                
                ablum.count = asset.count;
                ablum.headImageAsset = asset.firstObject;
                ablum.assetCollection = collection;
                [photoAblumList addObject:ablum];
                
                
            }
            
            
        }
        
        
    }];
    
    PHFetchResult *userAblum = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    
    [userAblum  enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL * _Nonnull stop)
     {
         
         __strong typeof(weakSelf) strongSelf = self;
         
         NSArray<PHAsset *> *assets = [strongSelf getAssetsInAssetCollection:collection ascending:NO];
         if (assets.count > 0) {
             SGPhotoAblumList *ablum = [[SGPhotoAblumList alloc]init];
             ablum.tittle = [strongSelf transFormPhotoTitle:collection.localizedTitle];
             ablum.count = assets.count;
             ablum.headImageAsset = assets.firstObject;
             ablum.assetCollection = collection;
             [photoAblumList addObject:ablum];
             
         }
         
         
     }];
    
    return photoAblumList;
}
//获取相册的文件名
-(NSString *)transFormPhotoTitle:(NSString *)englishName
{
    
    
    NSLog(@"%@",englishName);
    
    NSString *photoName;
    if ([englishName isEqualToString:@"Bursts"]) {
        photoName = @"连拍快照";
    }else if([englishName isEqualToString:@"Recently Added"]){
        photoName = @"最近添加";
    }else if([englishName isEqualToString:@"Screenshots"]){
        photoName = @"屏幕快照";
    }else if([englishName isEqualToString:@"Camera Roll"]){
        photoName = @"相机胶卷";
    }else if([englishName isEqualToString:@"Selfies"]){
        photoName = @"自拍";
    }else if([englishName isEqualToString:@"QQ"]){
        photoName = @"QQ";
    }else if([englishName isEqualToString:@"My Photo Stream"]){
        photoName = @"我的照片流";
    }else if([englishName isEqualToString:@"LHBrowerImage"]){
        photoName = @"测试";
    }else{
        photoName = [NSString stringWithFormat:@"%@",englishName];
    }
//    else if ([englishName ])
    return photoName;
}

#pragma mark - For all images within a specified album
- (NSArray<PHAsset *> *)getAssetsInAssetCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending
{
    NSMutableArray<PHAsset *>  *arr = [NSMutableArray  new];
    
    PHFetchResult *result = [self fetchAssetsInAssetCollection:assetCollection ascending:ascending];
    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (((PHAsset *)obj).mediaType == PHAssetMediaTypeImage) {
            [arr addObject:obj];
        }
     }];
    
    return arr;
}

-(PHFetchResult *)fetchAssetsInAssetCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending
{
    PHFetchOptions *option = [[PHFetchOptions alloc]init];
    
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];
    PHFetchResult *request = [PHAsset fetchAssetsInAssetCollection:assetCollection options:option];
    return request;
}



-(void)requestImageForAsset:(PHAsset *)asset size:(CGSize)size resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void (^)(UIImage *, NSDictionary *))completion
{
    
    static PHImageRequestID  requestID = -1;
    
    CGFloat scale = [UIScreen mainScreen].scale;
    
    CGFloat width = MIN([UIScreen mainScreen].bounds.size.width, kMaxImageWidth);
    
    if (requestID >= 1  && size.width/width == scale) {
        [[PHImageManager defaultManager]cancelImageRequest:requestID];
    }
    
    
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc]init];
    
    option.resizeMode = resizeMode;
    
    option.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    option.networkAccessAllowed = YES;
    
    
    requestID = [[PHCachingImageManager defaultManager]requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeAspectFit options:option resultHandler:^(UIImage * _Nullable image, NSDictionary * _Nullable info)
                 {
                     
                     BOOL downloadFinined = ![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey];
                     if (downloadFinined && completion) {
                         completion(image, info);
                     }
                     
                 }];
    
    
    
    
    
}
@end
